package cn.edu.scau.cmi.chenmiaopeng.hibernate.dao;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.hibernate.LockOptions;
import org.hibernate.Query;
import org.hibernate.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.hibernate.Transaction;

import cn.edu.scau.cmi.chenmiaopeng.hibernate.domain.Student;
import cn.edu.scau.cmi.chenmiaopeng.hibernate.domain.Teacher;
import cn.edu.scau.cmi.chenmiaopeng.hibernate.factory.HibernateSessionFactory;
public class TeacherDAO {
	private Session session;
	private static final Logger log = LoggerFactory.getLogger(TeacherDAO.class);
	// property constants
	public static final String NAME = "name";
	private String result = null;
	private Transaction transaction;
	public String getResult() {
	    return result;	
	}
	public void save(Teacher transientInstance) {  //新建老师
		session = HibernateSessionFactory.getSession();
		log.debug("saving Teacher instance");
		try {
			transaction = session.beginTransaction();
			session.save(transientInstance);
			transaction.commit();
			session.close();
			log.debug("save successful");
			result = "save successful!";
		} catch (RuntimeException re) {
			log.error("save failed", re);
			result = "save failed!";
			throw re;
		}
	}

	public void delete(Teacher persistentInstance) {  //删除老师
		session = HibernateSessionFactory.getSession();  //select update delete
		log.debug("deleting Teacher instance");
		try {
			transaction = session.beginTransaction();
			session.delete(persistentInstance);
			transaction.commit();
			session.close();
			log.debug("delete successful");
			result = "delete successful!";
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			result = "delete failed!";
			throw re;
		}
	}
	//修改老师姓名
		public void updateTeacherByName(Long teacherId, String newName) {
			session = HibernateSessionFactory.getSession();
			log.debug("update teacher instance");
			try {
				transaction = session.beginTransaction();
				Teacher instance = (Teacher)session.get("cn.edu.scau.cmi.chenmiaopeng.hibernate.domain.Teacher",teacherId);
				if(instance==null) {
                        result = "找不到该老师，请核实！";
						return ;
				}
				instance.setName(newName);
				session.update(instance);  //session.update(object o) 对对象进行更新
				transaction.commit();  //直接commit即可保存
				session.close();
				log.debug("update successful");
				result = "update successful!";
			} catch (RuntimeException re) {
				log.error("update failed", re);
				result = "update failed!";
				throw re;
			}
		}
		//修改老师工号和姓名：
		public void updateTeacherIdAndName(long oldId, long newId, String newName) {
			session = HibernateSessionFactory.getSession();
			transaction = session.beginTransaction();
			log.debug("update student instance");
			session.createSQLQuery("update teacher set id="+newId+", name='"+newName+"' where id = "+oldId).executeUpdate();
			transaction.commit();
			session.close();
		}
		//给老师增加指导学生  如果是student表里不存在的学生会怎样？ 一致性错误
		public void addStudent(long teacherId,Student addStu) {
			session = HibernateSessionFactory.getSession();
			log.debug("add student instance to teacher");
			try {
				transaction = session.beginTransaction();
				Teacher tea_instance = (Teacher)session.get("cn.edu.scau.cmi.chenmiaopeng.hibernate.domain.Teacher",teacherId);
				//用Set<Student>返回学生的集合，以供插入和修改：
				Set<Student> instr_stus = tea_instance.getStudents();
				instr_stus.add(addStu);
				//增加了学生以后再保存更新
				session.update(tea_instance);  
				transaction.commit();  //直接commit即可保存
				session.close();
				log.debug("successful");
				result = "add instruct student successful!";
			} catch (RuntimeException re) {
				log.error("update failed", re);
				result = "add instruct student failed!";
				throw re;
			}
		}
		//给老师修改指导学生
		public void alterStudent(long teacherId,Student oldStu,Student newStu) {
			session = HibernateSessionFactory.getSession();
			log.debug("alter student instance to teacher");
			try {
				transaction = session.beginTransaction();
				Teacher tea_instance = (Teacher)session.get("cn.edu.scau.cmi.chenmiaopeng.hibernate.domain.Teacher",teacherId);
				//用Set<Student>返回学生的集合，以供插入和修改：
				Set<Student> instr_stus = tea_instance.getStudents();
				Iterator<?> stuIterator = instr_stus.iterator();
				
//				if(alterStu==null) {
//					System.out.println("老师没有该学生，请查证！");
//				}
				while(stuIterator.hasNext()) {
					Student thisStu = (Student)stuIterator.next();
					if(thisStu.getId()==oldStu.getId()) {
//						instr_stus.remove(oldStu);  //这里没有去除旧的学生,若要实现则要重写Student的equals()方法
						instr_stus.remove(thisStu); //这样应该会去除
						instr_stus.add(newStu);     //只是插入了新的学生，而且新的学生的指导老师（之前若有），会相应改变
						break;
					}
				}
				//增加了学生以后再保存更新
				session.update(tea_instance);  
				transaction.commit();  //直接commit即可保存
				session.close();
				log.debug("alter instruct student successful!");
				result = "alter instruct student successful!";
				} catch (RuntimeException re) {
				log.error("alter instruct student failed!", re);
				throw re;
			}
		}
		//给老师删除指导学生 teacherId对应老师 删除student
		public void deleteStudent(long teacherId,Student deleteStu) {
			session = HibernateSessionFactory.getSession();
			log.debug("alter student instance to teacher");
			try {
				transaction = session.beginTransaction();
				Teacher tea_instance = (Teacher)session.get("cn.edu.scau.cmi.chenmiaopeng.hibernate.domain.Teacher",teacherId);
				//用Set<Student>返回学生的集合，以供插入和修改：
				Set<Student> instr_stus = tea_instance.getStudents();
				Iterator<?> stuIterator = instr_stus.iterator();
				while(stuIterator.hasNext()) {
					Student thisStu = (Student)stuIterator.next();
					if(thisStu.getId()==deleteStu.getId()) {
						instr_stus.remove(thisStu);
						break;
					}
				}
				session.update(tea_instance);  
				transaction.commit();  //直接commit即可保存
				session.close();
				log.debug("delete insturct student successful!");
				result = "delete insturct student successful!";
			} catch (RuntimeException re) {
				log.error("delete insturct student failed!", re);
				result = "delete insturct student failed!";
				throw re;
			}
		}
	public Teacher findById(java.lang.Long id) {  //查询老师
		session = HibernateSessionFactory.getSession();  //这里不要忘了getSession()
		log.debug("getting Teacher instance with id: " + id);
		try {
			Teacher instance = (Teacher)session.get("cn.edu.scau.cmi.chenmiaopeng.hibernate.domain.Teacher", id);
			//cn.edu.scau.cmi.chenmiaopeng.hibernate.domain.Teacher
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}
	
	public List findAll() {  //查询所有老师
		session = HibernateSessionFactory.getSession();
		log.debug("finding all Teacher instances");
		try {
			String queryString = "from Teacher";
			Query queryObject = session.createQuery(queryString);  //前面添加过一次之后，为什么这个getSession()又可以？
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}
	
}
//instance = (Teacher)session.get("cn.edu.scau.cmi.chenmiaopeng.hibernate.domain.Teacher",newName);
//if(instance==null) {  //不能修改老师id
//}